package com.zjs.timing;

import com.util.result.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * 定时任务控制器
 *
 * @author zhu_jinsheng
 * @version 1.0
 * @date 2020/7/7 13:57
 */
@Slf4j
@RestController
@RequestMapping("/scheduledTask")
public class ScheduledTaskController {
    public Message startScheduledTask() {
        return Message.success();
    }

    private static String DEFAULT_CRON = "0/5 * * * * ?";

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private ScheduledFuture<?> future;
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @PostMapping("/startCron")
    public String startCron() {
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger(DEFAULT_CRON));
        log.info("start cron");
        return "startCron";
    }

    @PostMapping("/stopCron")
    public String stopCron()  {
        if (future != null) {
            future.cancel(true);
        }
        log.info("stop cron");
        return "stopCron";
    }

    @PostMapping("/changeCron10")
    public String changeCron10() {
        stopCron();// 先停止，在开启.
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("*/10 * * * * *"));
        log.info("changeCron10");
        return "changeCron10";
    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            log.info("current run by DynamicTask");
        }
    }
}
